package mongo

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/cgs/app/models"
	v1 "cgs-server/server/cgs/app/models/v1"
	"cgs-server/server/cgs/app/store"
	"cgs-server/server/model"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
)

type publicWorksheet struct {
	db             *helper.Mongo
	collectionName string
}

func (w *publicWorksheet) Drop(wg *models.PublicWorksheet) error {
	collectionName := "ws" + wg.Id.Hex()
	return w.db.DropCollection(collectionName)
}

func (w *publicWorksheet) Save(wg *models.PublicWorksheet, user *model.User, opts v1.CreateOptions) error {
	wg.ResolveEntity(wg, user)
	_, err := w.db.InsertOne(w.collectionName, wg)
	return err
}

func (w *publicWorksheet) Get(wg *models.PublicWorksheet, user *model.User, opts v1.GetOptions) (*models.PublicWorksheet, error) {
	filter := opts.GetFilter()
	wg.ResolveFilter(wg, user, &filter)
	result := &models.PublicWorksheet{}
	find, err := w.db.FindOne(w.collectionName, filter, result)
	if !find {
		return nil, fmt.Errorf("worksheet info not found: %s", wg.GetId())
	}
	return result, err
}

func (w *publicWorksheet) Update(wg *models.PublicWorksheet, user *model.User, opts v1.UpdateOptions) error {
	filter := opts.GetFilter()

	wg.ResolveFilter(wg, user, &filter)
	set := bson.M{
		"receipt": wg.Receipt,
	}

	if wg.Enabled != nil {
		set["enabled"] = wg.Enabled
	}
	if wg.FieldSetting != nil {
		set["fieldSetting"] = wg.FieldSetting
	}
	if wg.FillTimes != nil {
		set["fillTimes"] = wg.FillTimes
	}
	if wg.Url != "" {
		set["url"] = wg.Url
	}
	if wg.Title != "" {
		set["title"] = wg.Title
	}
	if wg.Qrcode != "" {
		set["qrcode"] = wg.Qrcode
	}
	if wg.ShareId != "" {
		set["shareId"] = wg.ShareId
	}
	if wg.LastFillTime != nil {
		set["lastFillTime"] = wg.LastFillTime
	}
	if wg.ExtParam != nil {
		set["extParam.extField"] = wg.ExtParam.ExtField
	}

	wg.ResolveUpdateCondition(wg, user, &set)
	update := bson.M{
		"$set": set,
	}
	_, err := w.db.UpdateOne(w.collectionName, filter, update)
	return err
}

func (w *publicWorksheet) Delete(wg *models.PublicWorksheet, user *model.User, opts v1.DeleteOptions) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	}
	wg.ResolveFilter(wg, user, &filter)
	_, err := w.db.DeleteOne(w.collectionName, filter)
	return err
}

func newPublicWorksheetStore(d *datastore) store.PublicWorksheetStore {
	return &publicWorksheet{
		db:             d.db,
		collectionName: server.WorksheetPublicCollectionName,
	}
}
